﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Media.Imaging;
using Microsoft.Xna.Framework.Media;


namespace BootyShaker.Utils
{
    public class Imaging
    {   

        public static UInt32[] BGRAToRGBA(WriteableBitmap wb)
        {
            UInt32[] byteData = new UInt32[wb.Pixels.Length];
            for (int k = 0; k < wb.Pixels.Length; k++)
            {
                byteData[k] = (UInt32)wb.Pixels[k];
            }

            for (int i = 0; i < byteData.Length; i++)
            {
                byteData[i] = (((uint)byteData[i]) & 0x000000ff) << 16 | (byteData[i] & 0x0000FF00) | (byteData[i] & 0x00FF0000) >> 16 | (byteData[i] & 0xFF000000);
            }
            return byteData;
        }

        public void SaveImage(WriteableBitmap wb)
        {
            // Create a file name for the JPEG file in isolated storage.
            String tempJPEG = "TempJPEG";

            // Create a virtual store and file stream. Check for duplicate tempJPEG files.
            var myStore = IsolatedStorageFile.GetUserStoreForApplication();
            if (myStore.FileExists(tempJPEG))
            {
                myStore.DeleteFile(tempJPEG);
            }

            IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);

            // Encode the WriteableBitmap object to a JPEG stream.
            wb.SaveJpeg(myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
            myFileStream.Close();

            // Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.
            myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read);

            // Save the image to the camera roll or saved pictures album.
            MediaLibrary library = new MediaLibrary();


            // Save the image to the saved pictures album.
            Picture pic = library.SavePicture("SavedPicture.jpg", myFileStream);
            MessageBox.Show("Image saved to saved pictures album");
           
            myFileStream.Close();
        }

     

    }
}
